const express = require('express');
const note = require('../models/note');
const router = express.Router();

//添加笔记
router.post("/add-note" , (req , res) => {
  let body = req.body;
  const data = {
    title:body.title,
    id:body.id,
    classId:body.classId,
    content:body.content,
    brief:body.brief,
  };
  body.content && (data.brief = body.content.slice(0,44));
  if(!data.title){
    return resS(res , 'error' , '标题不能为空');
  };
  if(!data.classId){
    return resS(res , 'error' , '请选择栏目');
  };
  //判断是编辑还是新增
  if(data.id){
    data.pubdate = new Date().getTime();
    note.update({_id:data.id} , data , (error , date) => {
      if(error){
        resS(res , 'error' , '添加失败');
      }else{
        resS(res , 'ok' , '添加成功' , data);
      };
    });
  }else{
    note.add(data , (error , data) => {
      if(error){
        resS(res , 'error' , '添加失败');
      }else{
        resS(res , 'ok' , '添加成功' , data);
      }
    })
  };
});

//获取笔记
router.get('/note-list' , (req , res) => {
  if(!req.query.classId){
    return resS(res , 'error' , '请选择栏目');
  };
  note.get({classId:req.query.classId} , (error , data) => {
    if(error){
      resS(res , 'error' , '获取失败');
    }else{
      resS(res , 'ok' , '获取成功' , data);
    };
  });
});

//删除笔记
router.post('/del-note' , (req , res) => {
  note.remove({_id:req.body.id} , (error , data) => {
    if(error){
      resS(res , 'error' , '获取失败');
    }else{
      resS(res , 'ok' , '删除成功');
    };
  });
});

//移动笔记
router.post('/note-move' , (req , res) => {
  let id = req.body.id;
  let classId = req.body.classId;
  if(!id){
    return resS(res , 'error' , '请选择要移动的笔记');
  };
  if(!classId){
    return resS(res , 'error' , '请选择要移动到的分类');
  };
  note.update({_id:id} , {classId:classId} , (error , data) => {
    if(error){
      resS(res , 'error' , '操作失败');
    }else{
      resS(res , 'ok' , '移动成功');
    };
  });
});
function resS(res , state , msg , data){
  res.json({
    state:state,
    message:msg,
    data:data
  })
};
module.exports = router;
